<template>
  <div class="component amap_wrapper">
    <div id="amap_container"></div>
    <input id="tipInput" />
  </div>
</template>

<script lang="ts" setup>
import AMapLoader from '@amap/amap-jsapi-loader'

const props = withDefaults(defineProps<{
  width?: number | string
  height?: number | string
  plugins?: Array<string>
  defaultMarker?: any
}>(), {
  width: void 0,
  height: void 0,
  plugins: () => Array<string>(),
  defaultMarker: void 0
})

let map: any = void 0
let defaultPlugins = ['AMap.Geocoder', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Scale']

const emits = defineEmits<{ (e: '_placeSearch', address: String, pos: number[]): void }>()

const initMap = () => {

  const { width, height, plugins, defaultMarker } = toRefs(props)

  let wrapper = document.getElementsByClassName('amap_wrapper').item(0)

  if (wrapper) {

    if (width.value) wrapper.style.width = width.value + 'px'
    if (height.value) wrapper.style.height = height.value + 'px'

    AMapLoader.load({
      key: "97b243ce2c0fd9b1e4453f654a8429df",
      version: "2.0",
      plugins: defaultPlugins
    }).then((AMap) => {

      let marker: any = null

      map = new AMap.Map("amap_container", {
        viewMode: "3D",
        zoom: 11,
      })

      let geocoder = new AMap.Geocoder({
        city: '010',
        radius: 500
      })

      map.on('click', (e: any) => {
        if (marker) {
          marker.setMap(null)
          marker = null
        }

        let pos = [e.lnglat.KL || e.lnglat.lng, e.lnglat.kT || e.lnglat.lat]
        marker = new AMap.Marker({
          icon: new AMap.Icon({
            image: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            imageSize: new AMap.Size(24, 32),
          }),
          position: pos,
          offset: new AMap.Pixel(-13, -30)
        })
        if (marker) {
          marker.setMap(map)
          geocoder.getAddress(e.lnglat, function(status: any, result: any) {
            if (status === 'complete' && result.info === 'OK') {
              let formattedAddress = result.regeocode.formattedAddress
              if (formattedAddress) emits('_placeSearch', formattedAddress, pos)
            }
          })
        }
      })

      if (plugins.value.includes('PlaceSearch')) {
        AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], () => {
          let auto = new AMap.AutoComplete({
            input: "tipInput"
          })
          let placeSearch = new AMap.PlaceSearch({
            map: map
          })  //构造地点查询类
          auto.on("select", select) //注册监听，当选中某条记录时会触发
          function select(e: any) {
            placeSearch.setCity(e.poi.adcode)
            placeSearch.search(e.poi.name)
            let formattedAddress = e.poi.district + e.poi.address + e.poi.name
            let pos = [e.poi.location.KL || e.poi.location.lng, e.poi.location.kT || e.poi.location.lat]
            if (formattedAddress) emits('_placeSearch', formattedAddress, pos)
          }
        })
      }

      if (defaultMarker.value) {
        let pos = defaultMarker.value
        marker = new AMap.Marker({
          icon: new AMap.Icon({
            image: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            imageSize: new AMap.Size(24, 32),
          }),
          position: pos,
          offset: new AMap.Pixel(-13, -30)
        })
        marker.setMap(map)
        map.setCenter(pos)
      }
      // TODO any others

    }).catch((e) => {
      console.log(e)
    })

  }
}

onMounted(() => {
  initMap()
})

onUnmounted(() => {
  map?.destroy()
})
</script>

<style lang="less" scoped>
.component.amap_wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 8;
  #amap_container {
    width: 100%;
    height: 100%;
    z-index: 9;
  }
  #tipInput {
    border: 1px solid #ccc;
    width: 40%;
    max-width: 300px;
    height: 30px;
    line-height: 30px;
    padding: 0 8px;
    border-radius: 5px;
    position: absolute;
    right: 10px;
    top: 10px;
    z-index: 1024;
  }
}
</style>
